package com.example.notepadapp.ui;

import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.notepadapp.R;
import com.example.notepadapp.been.Notepad;
import com.example.notepadapp.databinding.ActivityEditBinding;
import com.example.notepadapp.databinding.ActivityMainBinding;
import com.example.notepadapp.db.DatabaseHelper;
import com.example.notepadapp.utils.TimeUtil;

import java.io.Serializable;

public class EditActivity extends AppCompatActivity {

    private ActivityEditBinding binding;
    DatabaseHelper databaseHelper;
    Notepad notepad;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityEditBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        databaseHelper = new DatabaseHelper(this);
        Serializable serializable = getIntent().getSerializableExtra("notepad");
        if (serializable == null){
            binding.tvTitle.setText("添加记录");
        }else{
            binding.tvTitle.setText("修改记录");
            notepad = (Notepad) serializable;
            binding.etContent.setText(notepad.getContent());
        }

        // 返回按钮
        binding.ivBack.setOnClickListener(v -> finish());
        // 清空输入框
        binding.ivDelete.setOnClickListener(v -> binding.etContent.setText(""));
        // 保存数据
        binding.ivSave.setOnClickListener(view -> {
            String content = binding.etContent.getText().toString();
            if (TextUtils.isEmpty(content)){
                Toast.makeText(this, "内容不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            // 判断是新增还是修改
            if (notepad == null){
                notepad = new Notepad();
                notepad.setContent(content);
                notepad.setTime(TimeUtil.getTime());
                databaseHelper.insert(notepad);
                Toast.makeText(this, "新增成功", Toast.LENGTH_SHORT).show();
            }else{
                notepad.setContent(content);
                notepad.setTime(TimeUtil.getTime());
                databaseHelper.update(notepad);
                Toast.makeText(this, "修改成功", Toast.LENGTH_SHORT).show();
            }

            setResult(RESULT_OK);
            finish();
        });
    }
}